package com.timestar.event;

import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;

/**
 * Created by zxn on 2025/2/7.
 */
public class LiveDataBus {

    private final MutableLiveData<EventData> mLiveData;

    public LiveDataBus() {
        mLiveData = new MutableLiveData<>();
    }

    static volatile LiveDataBus defaultInstance;

    public static LiveDataBus getDefault() {
        LiveDataBus instance = defaultInstance;
        if (instance == null) {
            synchronized (LiveDataBus.class) {
                instance = LiveDataBus.defaultInstance;
                if (instance == null) {
                    instance = LiveDataBus.defaultInstance = new LiveDataBus();
                }
            }
        }
        return instance;
    }

    public void register(@NonNull LifecycleOwner owner, @NonNull Observer<EventData> observer) {
        mLiveData.observe(owner, observer);
    }

    public synchronized void unregister(@NonNull final LifecycleOwner owner) {
        mLiveData.removeObservers(owner);
    }

    public void post(EventData event) {
        mLiveData.setValue(event);
    }

}
